import {createRouter, createWebHashHistory} from "vue-router";
import { useUserStore } from '@/store/user';

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/login',
            name: 'login',
            component: () => import('@/views/Login.vue'),
            meta: { requiresAuth: false }
        },
        {
            path: '/register',
            name: 'register',
            component: () => import('../views/Register.vue'),
            meta: { requiresAuth: false }
        },
        {
            path: '/',
            component: () => import('@/layouts/DefaultLayout.vue'),
            children: [
                {
                    path: '',
                    name: 'home',
                    component: () => import('../views/Home.vue'),
                    meta: { requiresAuth: true }
                }
                // 可以在这里添加更多需要DefaultLayout的路由
            ]
        },
        // 404页面
        {
            path: '/:pathMatch(.*)*',
            redirect: '/'
        }
    ]
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
    const userStore = useUserStore();
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
    
    if (requiresAuth && !userStore.user) {
        next('/login');
    } else {
        next();
    }
});

export default router;